class Admin::OperatorsController < AdminApplicationController
  skip_before_action :authenticate_login
  layout 'login_layout'

  def sign_in
    @operator = Operator.new
  end

  def login
    operator = Operator.find_by_name(operator_params[:name])
    if operator.nil?
      @notice = '用户名不存在'
      @operator = Operator.new(:name => operator_params[:name])
      render 'admin/operators/sign_in' and return
    end
    operator = Operator.where('name = ? and passwd = ? ',operator_params[:name],operator_params[:passwd])
    if operator.empty?
      @notice = ''
      @operator = Operator.new(:name => operator_params[:name])
      operator = Operator.find_by_name(operator_params[:name])
      if !operator.is_locked
        if operator.failed_times >= 3
          @notice = '错误次数过多,该用户已被锁'
          operator.update(is_locked: true)
          render 'admin/operators/sign_in' and return
        else
          @notice = "密码错误,还剩下#{3-operator.failed_times-1}次尝试"
          operator.update(failed_times: operator.failed_times+1)
          render 'admin/operators/sign_in' and return
        end
      else
        @notice = '该用户已被锁,请联系管理员解锁'
        render 'admin/operators/sign_in' and return
      end
    else
      cookies[:LoginUserInfo] ={
          value: operator.name,
          expires: 30.minutes.from_now
      }
      redirect_to '/admin',notice: '登陆成功'
    end
  end

  def logout
    cookies[:LoginUserInfo].delete
    redirect_to '/admin/operator_sign_in'
  end

  private
    def operator_params
      params.require(:operator).permit(:name,:passwd)
    end
end